package com.dc.aimc.gateway.filter;

import com.dc.aimc.common.service.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GatewayFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 放行api文档路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (path.equals("/v2/api-docs")) {
            return chain.filter(exchange);
        }
        // 是否携带 access-token, tenant-id
        HttpHeaders headers = request.getHeaders();
        String authorization = headers.getFirst("Authorization");
        if (StringUtils.isEmpty(authorization) || StringUtils.isEmpty(authorization)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        boolean verifyToken = JwtUtil.verifyToken(authorization.split(" ")[1]);
        if(!verifyToken) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
}
